package com.qh.yyxt.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class QrCodeUtils {
    //private static final String CHARSET = "utf-8";
    //public static final String FORMAT = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 1000;
    // LOGO宽度
    private static final int LOGO_WIDTH1 = 100;
    // LOGO高度
    private static final int LOGO_HEIGHT1 = 100;
    private static final int LOGO_WIDTH2 = 1000;
    // LOGO高度
    private static final int LOGO_HEIGHT2 = 250;
    public static void exportQuickResponseCode(HttpServletRequest request, HttpServletResponse response, String sign) throws Exception{
//        String msg = sign+" ";
        String msg = sign;
        String filename = sign+".png";
        String path = "C:/ewm/" + filename;//二维码图片路径
//        String path = "/QrCode/img/"+filename;
//        String temDir = "D:/test/";
//        File dir = new File(temDir);
//        if (!dir.exists()) {
//            dir.mkdirs();
//        }
        //String path = "D:/test/" + filename;
        String orgText = "大学生事务服务中心";
        String goodsNameText = sign;
        try {
            File file = new File(path);
            OutputStream ous = new FileOutputStream(file);
            Map<EncodeHintType, String> map = new HashMap<EncodeHintType, String>();
            //设置编码 EncodeHintType类中可以设置MAX_SIZE， ERROR_CORRECTION，CHARACTER_SET，DATA_MATRIX_SHAPE，AZTEC_LAYERS等参数
            map.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            map.put(EncodeHintType.MARGIN, "2");
            //生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(msg, BarcodeFormat.QR_CODE, 1000, 1000, map);
            MatrixToImageWriter.writeToStream(bitMatrix, "png", ous);
            // 绘制图片
            BufferedImage backgroundImage = new BufferedImage(1100, 1200, BufferedImage.TYPE_INT_RGB);
            BufferedImage image = ImageIO.read(file);
            Graphics2D rng = backgroundImage.createGraphics();
            rng.setColor(new Color(253, 252, 252, 255));//设置笔刷颜色
            rng.fillRect(0, 0, 1100, 1200);
            rng.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
            rng.drawImage(image, 200, 250, 600, 600, null);
            // 绘制文字
            rng.setColor(Color.black);
            rng.setFont(new Font("黑体", Font.BOLD, 75));
            rng.drawString(orgText, (300) / 2, 220);
            rng.drawString(goodsNameText, (850) / 2, 1000);
            rng.dispose();
            image = backgroundImage;
            QrCodeUtils.insertImage1(image, "/QR/1.jpg", true);
            QrCodeUtils.insertImage2(image, "/QR/2.jpg", true);
            image.flush();
            ImageIO.write(image, "png", file);
            ous.close();
            // 以下是下载图片
            // 当文件名不是英文名的时候，最好使用url解码器去编码一下，
//            filename= URLEncoder.encode(filename,"UTF-8");
//            // 将响应的类型设置为图片
//            response.setContentType("image/png");
//            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
//            FileInputStream fileInputStream = new FileInputStream(file);
//            OutputStream out = response.getOutputStream();
//            int len = 0;
//            byte[] by = new byte[1024*10];
//            while ((len = fileInputStream.read(by))>0){
//                out.write(by,0,len);
//            }
//            out.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        }
    public static void delFileWord(String filePath, String fileName){//删除文件
        File file =new File(filePath+fileName);
        File file1 =new File(filePath);
        file.delete();
        file1.delete();
    }
    private static void insertImage1(BufferedImage source, String logoPath, boolean needCompress) throws IOException {
        InputStream inputStream = null;
        try {
            inputStream = QrCodeUtils.getResourceAsStream(logoPath);
            Image src = ImageIO.read(inputStream);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            if (needCompress) { // 压缩LOGO
                if (width > LOGO_WIDTH1) {
                    width = LOGO_WIDTH1;
                }
                if (height > LOGO_HEIGHT1) {
                    height = LOGO_HEIGHT1;
                }
                Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(image, 0, 0, null); // 绘制缩小后的图
                g.dispose();
                src = image;
            }
            // 插入LOGO
            Graphics2D graph = source.createGraphics();
            int x = (QRCODE_SIZE - width) / 2;
            int y = (QRCODE_SIZE - height) / 2+50;
            graph.drawImage(src, x, y, width, height, null);
            Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
            graph.setStroke(new BasicStroke(3f));
            graph.draw(shape);
            graph.dispose();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
    private static void insertImage2(BufferedImage source, String logoPath, boolean needCompress) throws IOException {
        InputStream inputStream = null;
        try {
            inputStream = QrCodeUtils.getResourceAsStream(logoPath);
            Image src = ImageIO.read(inputStream);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            if (needCompress) { // 压缩LOGO
                if (width > LOGO_WIDTH2) {
                    width = LOGO_WIDTH2;
                }
                if (height > LOGO_HEIGHT2) {
                    height = LOGO_HEIGHT2+10;
                }
                Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(image, 0, 0, null); // 绘制缩小后的图
                g.dispose();
                src = image;
            }
            // 插入LOGO
            Graphics2D graph = source.createGraphics();
            int x = 60;
            int y = 30;
            graph.drawImage(src, x, y, width, height, null);
            Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
            graph.setStroke(new BasicStroke(3f));
            graph.draw(shape);
            graph.dispose();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
    public static InputStream getResourceAsStream(String logoPath) {
        return QrCodeUtils.class.getResourceAsStream(logoPath);
    }

}
